import Player from 'xgplayer';
import HlsJsPlayer from 'xgplayer-hls.js';
//西瓜视频播放器
let errorT = 0;
//let sh = 0;
function getXgplayerConfig(dId, videoObj) {
  //videoObj所需所有参数videoMp4，videoM3U8，autoplay，fluid，isCssFullScreen，poster
  //let isMobile = !!window.navigator.userAgent.match(/AppleWebKit.*Mobile.*/); //是否为移动终端
  //let isWA = isMobile && !navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) && window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) != 'micromessenger' ? true : false; //判断是不是移动端但是不是微信内
  // if (isWA) {
  //   alert("此浏览器暂不支持播放视频，请去微信内或者pc电脑端打开该课程进行观看视频！");
  //   return;
  // }
  let xgPlayer = null;
  let u = window.navigator.userAgent;
  let clientW = document.documentElement.clientWidth > 640 ? 640 : document.documentElement.clientWidth;
  let videoH = videoObj.isFromMicro ? videoObj.height : clientW / 320 * 180;
  let ignoreArr = ['volume', 'replay'];
  let surl = videoObj.videoMp4;
  if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    surl = videoObj.videoM3U8;
  }
  if (videoObj.isCssFullScreen) {
    ignoreArr = ['fullscreen', 'volume', 'replay']
  }
  //如果是pc端，默认都是用m3u8de,如果没有m3u8的那么使用mp4的，防止mp4没有转码，导致的只有声音没有图像
  let isMobile = !!u.match(/AppleWebKit.*Mobile.*/); //是否为移动终端
  let isiOS = u.indexOf('IOSLogin') > -1; //ios终端
  let isNewiOS = u.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1; //ios终端
  if (!isMobile && surl.indexOf(".mp4") > -1 && !isiOS && !isNewiOS) {
    if (videoObj.videoM3U8 && videoObj.videoM3U8.indexOf(".m3u8") > -1) {
      surl = videoObj.videoM3U8;
    }
  }
  surl = surl.indexOf("http://") != -1 ? surl.replace("http://", "https://") : surl;
  //let andAndM3u8 = (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) && surl.indexOf(".m3u8") > -1 ? true : false;
  let xgConfig = {
    id: dId,
    url: surl,
    poster: videoObj.poster ? videoObj.poster : '',
    width: clientW,
    height: videoH,
    autoplay: videoObj.autoplay ? videoObj.autoplay : false,
    playbackRate: videoObj.isPlaybackRate ? '' : [0.5, 0.75, 1, 1.25, 1.5, 2], //andAndM3u8 || videoObj.isPlaybackRate ? '' : [0.5, 0.75, 1, 1.25, 1.5, 2],
    defaultPlaybackRate: 1,
    cssFullscreen: videoObj.isCssFullScreen ? videoObj.isCssFullScreen : false,
    controls: true,
    controlsList: ['nodownload', 'noremoteplayback'],
    ignores: ignoreArr,
    videoInit: videoObj.videoInit == -1 ? false : true,
    whitelist: [''],
    closeVideoClick: true,
    closeVideoDblclick: true,
    closeVideoTouch: true,
    closePlayerBlur: true,
    closeFocusVideoFocus: true,
    closePlayVideoFocus: true,
    enableContextmenu: false,
    allowPlayAfterEnded: true,
    allowSeekAfterEnded: true,
    closeVideoStopPropagation: true,
    rotate: { //视频旋转按钮配置项
      innerRotate: true, //只旋转内部video
      clockwise: true // 旋转方向是否为顺时针
    },
    allowSeekPlayed: videoObj.allowSeekPlayed ? videoObj.allowSeekPlayed : false,
    loop: videoObj.loop ? videoObj.loop : false,
    allowFastForward: videoObj.allowFastForward ? videoObj.allowFastForward : false,
  }
  console.log('----xgConfig----', xgConfig)
  if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    xgConfig.playsinline = true;
    xgConfig.airplay = true;
  } else {
    xgConfig['x5-video-player-type'] = 'h5-page';
    xgConfig['x5-video-orientation'] = 'landscape|portrait';
  }
  if (videoObj.fluid && videoObj.fluid == true) {
    xgConfig.fluid = true;
  }

  if (xgConfig.url.indexOf(".m3u8") > -1 && !isMobile) {
    xgConfig.useHls = true;
    xgConfig.crossOrigin = "anonymous";
    xgPlayer = new HlsJsPlayer(xgConfig);
  } else {
    xgPlayer = new Player(xgConfig);
  }
  xgPlayer.on("requestCssFullscreen", () => {
    document.querySelector(".xgplayer-skin-default .xgplayer-controls").style.bottom = "16px";
    xgPlayer.video.style.cssText = 'position: absolute; top: 0px; left: 0px;';
  });
  xgPlayer.on("exitCssFullscreen", () => {
    document.querySelector(".xgplayer-skin-default .xgplayer-controls").style.bottom = "0";
    xgPlayer.video.style.cssText = 'position: absolute; top: 0px; left: 0px;';
  });

  errorT = 0;
  xgPlayer.on("error", (e) => {
    console.log("视频加载出错", e);
    if (errorT == 2) {
      console.log("视频加载出错，请稍后再试");
      return;
    }
    if (e && e.errd && e.errd.msg) {
      let esd = "#" + dId + ' .xgplayer-error';
      let esdQ = document.querySelector(esd);
      if (esdQ.querySelector(".xgplayer-error-text")) {
        esdQ.querySelector(".xgplayer-error-text").innerHTML = e.errd.msg;
      }
    }
    if (xgConfig.url.indexOf(".mp4") > -1) {
      if (xgConfig.url == videoObj.videoM3U8 || videoObj.videoM3U8.indexOf(".m3u8") == -1) {
        return;
      }
      let id = "#" + dId;
      document.querySelector(id).innerHTML = videoObj.marqueConf ? videoObj.marqueConf : ""; //如果有跑马灯样式，要引入跑马灯
      videoObj.videoM3U8 = videoObj.videoM3U8.indexOf("http://") != -1 ? videoObj.videoM3U8.replace("http://", "https://") : videoObj.videoM3U8;
      xgConfig.url = videoObj.videoM3U8;
      xgConfig.playbackRate = (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) ? '' : [0.5, 0.75, 1, 1.25, 1.5, 2];
      if (!isMobile) {
        xgPlayer = new HlsJsPlayer(xgConfig);
      } else {
        xgPlayer = new Player(xgConfig);
      }
      errorT = 1;
    } else {
      if (xgConfig.url == videoObj.videoMp4 || videoObj.videoMp4.indexOf(".mp4") == -1) {
        return;
      }
      let id = "#" + dId;
      document.querySelector(id).innerHTML = videoObj.marqueConf ? videoObj.marqueConf : ""; //如果有跑马灯样式，要引入跑马灯
      videoObj.videoMp4 = videoObj.videoMp4.indexOf("http://") != -1 ? videoObj.videoMp4.replace("http://", "https://") : videoObj.videoMp4;
      xgConfig.url = videoObj.videoMp4;
      xgPlayer = new Player(xgConfig);
      errorT = 2;
    }
  });
  xgPlayer.playerType = "xg";
  return xgPlayer;
}

// 腾讯云超级播放器创建video dom
function createVideoDom(dId, tcConfig) {
  // 创建video标签，方便全局替换
  let dIdObj = document.getElementById(dId);
  //如果加密失败或则加密中，提示图片内容
  if (tcConfig.adpStatus == -1 || tcConfig.adpStatus == 1) {
    dIdObj.innerHTML = `<img src="https://ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com/admin/material/9_material_admin/image/assets/adp_img.png" class="c-w100 c-hh360" />`;
    return;
  }
  let videoDoc = document.createElement("video");
  videoDoc.setAttribute("id", `${dId}TcP`);
  videoDoc.setAttribute("preload", "auto");
  videoDoc.setAttribute("crossorigin", 'anonymous');
  videoDoc.setAttribute("playsinline", '');
  videoDoc.setAttribute("webkit-playsinline", '');
  if (window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { // 支持使用苹果airplay
    videoDoc.setAttribute("x-webkit-airplay", "allow");
  }
  // 这个是为了匹配西瓜播放器创建的dom
  videoDoc.className = dIdObj.className;
  videoDoc.style = dIdObj.style;
  /* dIdObj.className = '';
  dIdObj.style = ''; */
  if (!document.getElementById(`${dId}TcP`)) {
    dIdObj.appendChild(videoDoc);
  }
}

// 腾讯云超级播放器
function getTcplayerConfig(dId, videoObj) {
  let winW = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
  let clientW = winW > 640 ? 640 : winW;
  let videoH = videoObj.isFromMicro ? videoObj.height : (clientW / 320) * 180;

  let u = window.navigator.userAgent;
  let isMobile = !!u.match(/AppleWebKit.*Mobile.*/); //是否为移动终端
  let tcConfig = {
    poster: videoObj.poster ? videoObj.poster : '',
    posterImage: videoObj.poster ? true : false,
    width: videoObj.isFromMicro && videoObj.customWidth ? videoObj.customWidth : clientW,
    height: videoH,
    autoplay: videoObj.autoplay ? videoObj.autoplay : false,
    bigPlayButton: videoObj.isFromMicro ? true : false, //播放按钮是否显示
    controls: true, // Boolean
    controlBar: {
      QualitySwitcherMenuButton: false,
      volumePanel: false,
      fullscreenToggle: true
    },
    hlsConfig: {
      maxBufferLength: 20, // 默认30秒
      maxBufferSize: 40 * 1024 * 1024, // 默认60MB
      maxMaxBufferLength: 60 // 默认600秒
    },
    /* hlsConfig: { // 如果出现hls.js和浏览器兼容有问题的情况
      disable: isMobile ? true : false
    }, */
    fakeFullscreen: videoObj.isCssFullScreen ? videoObj.isCssFullScreen : false, // 伪全屏
    playbackRates: videoObj.isPlaybackRate ? '' : [0.5, 0.75, 1, 1.25, 1.5, 2],
    loop: videoObj.loop ? videoObj.loop : false,
    plugins: videoObj.plugins ? videoObj.plugins : {}
    // licenseUrl: "https://license.vod2.myqcloud.com/license/v2/1301306398_1/v_cube.license" // 这个是超级播放器是5.0需要的
  }

  try { // 判断是不是以http开头的链接地址，如果不是就转成json对象，如果转换失败，那么还是按字符串走
    if (videoObj.videoMp4) videoObj.videoMp4 = videoObj.videoMp4.indexOf("https://") == 0 || videoObj.videoMp4.indexOf("http://") == 0 ? videoObj.videoMp4 : JSON.parse(videoObj.videoMp4);
    if (videoObj.videoM3U8) videoObj.videoM3U8 = videoObj.videoM3U8.indexOf("https://") == 0 || videoObj.videoM3U8.indexOf("http://") == 0 ? videoObj.videoM3U8 : JSON.parse(videoObj.videoM3U8);
  } catch (error) {
    console.log("不是json格式的话，那么就还走字符串的形式");
  }

  if ((typeof videoObj.videoMp4 == "object") || (typeof videoObj.videoM3U8 == "object")) {
    let afp = null;
    if (videoObj.videoMp4 && videoObj.videoMp4.fileID && videoObj.videoMp4.fileID.length > 0 && videoObj.videoMp4.appID) {
      videoObj.fileID = videoObj.videoMp4.fileID;
      afp = videoObj.videoMp4;
    } else if (videoObj.videoM3U8 && videoObj.videoM3U8.fileID && videoObj.videoM3U8.fileID.length > 0 && videoObj.videoM3U8.appID) {
      videoObj.fileID = videoObj.videoM3U8.fileID;
      afp = videoObj.videoM3U8;
    }
    console.log('---解密后--', afp)
    if (afp) {
      tcConfig.appID = afp.appID || '';
      tcConfig.fileID = afp.fileID || '';
      tcConfig.adpStatus = afp.adpStatus || '';
      if (afp.psign) tcConfig.psign = afp.psign || ''; // 加密流要有这
    }
  }

  // 先销毁播放器，防止播放器之前创建过，但未销毁
  let players = TCPlayer.players; // eslint-disable-line
  if (players && players[`${dId}TcP`]) {
    let playerObj = players[`${dId}TcP`];
    if (playerObj) {
      playerObj.dispose();
    }
  }

  // 创建video标签，方便全局替换
  createVideoDom(dId, tcConfig);

  if (tcConfig.adpStatus == -1) {
    return;
  }

  let tcPlayer = null;
  tcPlayer = TCPlayer(`${dId}TcP`, tcConfig); // eslint-disable-line

  let surl = !videoObj.fileID ? videoObj.videoMp4 : '';
  if (!videoObj.fileID && u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    surl = videoObj.videoM3U8;
  }

  //如果是pc端，默认都是用m3u8de,如果没有m3u8的那么使用mp4的，防止mp4没有转码，导致的只有声音没有图像
  let isiOS = u.indexOf('IOSLogin') > -1; //ios终端
  let isNewiOS = u.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1; //ios终端
  if (!videoObj.fileID && !isMobile && surl.indexOf(".mp4") > -1 && !isiOS && !isNewiOS) {
    if (videoObj.videoM3U8 && videoObj.videoM3U8.indexOf(".m3u8") > -1) {
      surl = videoObj.videoM3U8;
    }
  }

  if (surl != '') { // 没有fileId的话走src进行播放
    surl = surl.indexOf("http://") != -1 ? surl.replace("http://", "https://") : surl;
    tcPlayer.src(surl); // url 播放地址
  }

  tcPlayer.ready(() => {
    if (videoObj.allowFastForward) {
      let rateElememt = tcPlayer.controlBar.el_.querySelector(".vjs-playback-rate")
      let rewindElement = createRewindBtn();
      let forwardElement = createForwardBtn();
      rewindElement.addEventListener("click", () => {
        videoObj.fastRewindCB && videoObj.fastRewindCB.call(videoObj.playerCtx);
      }, false);
      forwardElement.addEventListener("click", () => {
        videoObj.fastForwardCB && videoObj.fastForwardCB.call(videoObj.playerCtx);
      }, false);
      tcPlayer.controlBar.el_.insertBefore(rewindElement, rateElememt)
      tcPlayer.controlBar.el_.insertBefore(forwardElement, rateElememt)
    }
    if (videoObj.isCssFullScreen && videoObj.rotateScreenToggle != false) { //伪全屏默认都开启旋转按钮，除非特别指定不开启
      //是否开启全屏旋转按钮
      let beforeRotateElem = createBeforeRotateElem();
      let afterRotateElem = createAfterRotateElem();
      beforeRotateElem.style.display = "none";
      afterRotateElem.style.display = "none";
      beforeRotateElem.addEventListener("click", () => {
        rotateVideo(tcPlayer);
        videoObj.rotateVideoCB && videoObj.rotateVideoCB.call(videoObj.playerCtx);
      }, false);
      afterRotateElem.addEventListener("click", () => {
        recoverRotateVideo(tcPlayer);
        videoObj.recoverRotateVideoCB && videoObj.recoverRotateVideoCB.call(videoObj.playerCtx);
      }, false);
      tcPlayer.controlBar.el_.appendChild(beforeRotateElem);
      tcPlayer.controlBar.el_.appendChild(afterRotateElem);
      tcPlayer._beforeRotateElem = beforeRotateElem;
      tcPlayer._afterRotateElem = afterRotateElem;
    }
    /* if (videoObj.isCssFullScreen && !document.querySelector(`#${dId}TcP .css-full-icon`)) { // 伪全屏， 超级播放器4.7一下的不支持，所以自写
      let cssFullElem = document.createElement('button');
      let cssFullIconElem = document.createElement('span');
      cssFullElem.setAttribute("type", "button");
      cssFullElem.className = 'css-full-icon vjs-control vjs-button';
      cssFullIconElem.className = 'full-icon iconfont icon-quanping1';
      cssFullElem.appendChild(cssFullIconElem);
      tcPlayer && tcPlayer.controlBar.el_.appendChild(cssFullElem);

      let fullScreenButton = document.querySelector(`#${dId}TcP .css-full-icon`);
      if (fullScreenButton) {
        fullScreenButton.addEventListener("click", (e) => {
          if (document.getElementById(`${dId}TcP`).className.indexOf("tcCssFullScreen") > -1) {
            if (videoObj.fluid) { // 设置标签的宽高 类似于流式布局
              tcPlayer.fluid(true);
            }
            document.getElementById(`${dId}TcP`).className = document.getElementById(`${dId}TcP`).className.replace(" tcCssFullScreen", "");
            tcPlayer.width(clientW);
            tcPlayer.height(videoH);
          } else {
            if (videoObj.fluid) { // 设置标签的宽高 类似于流式布局
              tcPlayer.fluid(false);
            }
            document.getElementById(`${dId}TcP`).className += " tcCssFullScreen";
            let winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            tcPlayer.width(winW);
            tcPlayer.height(winH);
          }
        })
      }
    } */
  });

  // 监听自动播放被阻止
  tcPlayer.on("blocked", (e) => {
    console.log("blockedblockedblockedblocked");
    // 微信环境下苹果系统12fileId的情况下播放自动播放被阻止
    if (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger' && navigator.userAgent.toLowerCase().indexOf('mac') > -1 && (window.navigator.userAgent.toLowerCase().indexOf("12_") > -1)) {
      try {
        document.addEventListener("WeixinJSBridgeReady", () => {
          tcPlayer.play();
        }, false);
        WeixinJSBridge.invoke("getNetworkType", {}, () => {// eslint-disable-line
          tcPlayer.play();
        });
      } catch (error) {
        console.log("WeixinJSBridge不兼容");
      }
    } else {
      tcPlayer.play();
    }
  });

  tcPlayer.on("fullscreenchange", (e) => {
    if (videoObj.isCssFullScreen) { // 超级播放器4.8.0版本伪全屏还有问题
      // 跟超级播放器5.0设置的样式一致
      if (tcPlayer.isFullscreen()) {
        document.querySelector(`#${dId}TcP`).style = "width:100vw;height:100%;position:fixed;z-index:999;top:0;left:0;overflow-y:hidden;";
      } else {
        document.querySelector(`#${dId}TcP`).style = "";
      }
    }
    if (videoObj.isCssFullScreen && videoObj.rotateScreenToggle != false) {
      if (tcPlayer.isFullscreen()) {
        //全屏
        tcPlayer._beforeRotateElem.style.display = "flex";
        tcPlayer._afterRotateElem.style.display = "none";
      } else {
        //非全屏
        recoverRotateVideo(tcPlayer);
        tcPlayer._beforeRotateElem.style.display = "none";
        tcPlayer._afterRotateElem.style.display = "none";
      }
    }
  });

  tcPlayer.on("error", (e) => {
    // 视频加载出错如何处理？如何切换视频源
    console.log("腾讯云播放器报错了!!!", e);
    let code = e.data.code;
    if (!videoObj.fileID && (code == 4 || code == 3 || code == 13)) { // 切换视频源进行播放
      if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        if (surl.indexOf(".m3u8") > -1 && videoObj.videoMp4 && videoObj.videoMp4.indexOf(".mp4") > -1) {
          surl = videoObj.videoMp4;
          tcPlayer.src(surl); // url 播放地址
        }
      } else {
        if (surl.indexOf(".mp4") > -1 && videoObj.videoM3U8 && videoObj.videoM3U8.indexOf(".m3u8") > -1) {
          surl = videoObj.videoM3U8;
          tcPlayer.src(surl); // url 播放地址
        }
      }
    } else if (!videoObj.fileID && code == 14 && surl.indexOf("1252433846.vod2.myqcloud.com") > -1) {
      let sct = 0;
      try {
        sct = e.data.source.frag.start;
      } catch (e) {
        sct = 0;
      }
      surl = surl.replace("1252433846.vod2.myqcloud.com", "txvod125.ckjrio.com");
      tcPlayer.src(surl); // url 播放地址
      setTimeout(() => {
        tcPlayer.currentTime(parseInt(sct));
        tcPlayer.play();
      }, 300);
    }
  });
  tcPlayer.playerType = "tc";
  return tcPlayer;
}

//创建快退15秒的按钮
function createRewindBtn() {
  let wrapElem = document.createElement('div');
  let elem = document.createElement("span");
  wrapElem.className = "vjs-control c-flex-row c-justify-center c-lh-167 forward-btn"
  elem.className = "item item-fast-forward iconfont icon-kuaitui15miao";
  wrapElem.appendChild(elem);
  return wrapElem;
}

//创建快进15秒的按钮
function createForwardBtn() {
  let wrapElem = document.createElement('div');
  let elem = document.createElement("span");
  wrapElem.className = "vjs-control c-flex-row c-justify-center c-lh-167 forward-btn"
  elem.className = "item item-fast-forward iconfont icon-kuaijin15miao";
  wrapElem.appendChild(elem);
  return wrapElem;
}

//创建旋转前的按钮
function createBeforeRotateElem() {
  let wrapElem = document.createElement('div');
  let elem = document.createElement("span");
  wrapElem.className = "video-rotate"
  elem.className = "item item-rotate iconfont icon-tcplayer-pingmuxuanzhuan";
  wrapElem.appendChild(elem);
  return wrapElem;
}
//创建旋转后的按钮
function createAfterRotateElem() {
  let wrapElem = document.createElement('div');
  let elem = document.createElement("span");
  wrapElem.className = "video-rotate"
  elem.className = "item item-rotate iconfont icon-tcplayer-pingmuxuanzhuan";
  wrapElem.appendChild(elem);
  return wrapElem;
}

//旋转函数
function rotateVideo(player) {
  let winH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  let winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  let videoElem = document.getElementById(player.children_[0].id);
  const offset = winH - winW;
  let offsetX = -offset / 2;
  let offsetY = offset / 2;
  videoElem.style.width = `${winH}px`;
  videoElem.style.height = `${winW}px`;
  videoElem.style.transformOrigin = "center center";
  videoElem.style.transform = `translate(${offsetX}px,${offsetY}px) rotate(90deg)`;
  player._beforeRotateElem.style.display = 'none';
  player._afterRotateElem.style.display = 'flex';
}
//恢复旋转函数
function recoverRotateVideo(player) {
  let videoElem = document.getElementById(player.children_[0].id);
  videoElem.style.width = "100%";
  videoElem.style.height = "100%";
  videoElem.style.transform = "";
  player._beforeRotateElem.style.display = 'flex';
  player._afterRotateElem.style.display = 'none';
}

//创建播放器
export function getXgplayer(dId, videoObj, playerType = "tc") {
  if (playerType == "xg") {
    return getXgplayerConfig(dId, videoObj); // 西瓜播放器
  } else {
    return getTcplayerConfig(dId, videoObj); // 腾讯云超级播放器
  }
}

// 销毁播放器
export function destoryPlayer(player) {
  if (player) {
    if (player.playerType == "xg") {
      player.destroy(); // 西瓜播放器
    } else {
      /* let fullScreenButton = document.querySelector(`#${player.id_} .css-full-icon`);
      fullScreenButton && fullScreenButton.removeEventListener("click", () => {}); */
      // 判断视频是否全屏伪全屏，伪全屏则先退出全屏
      if (player.options_ && player.options_.fakeFullscreen && player.isFullscreen()) {
        player.exitFullscreen()
      }
      player.dispose(); // 腾讯云超级播放器
    }
  }
}
